/*
 * @Author: wangwei wwdqq7@qq.com
 * @Date: 2025-04-01 14:10:00
 * @LastEditors: wangwei wwdqq7@qq.com
 * @LastEditTime: 2025-04-01 14:10:00
 * @FilePath: /FullStack/pro/typeorm-mysql/src/user/permission.service.ts
 * @Description: 权限服务，提供权限管理的业务逻辑
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { DatabaseAccess } from '@/entity/DatabaseAccess';
import { Permission } from '@/entity/Permission';
import { Role } from '@/entity/Role';
import { RolePermission } from '@/entity/RolePermission';
import { TableAccess } from '@/entity/TableAccess';
import { User } from '@/entity/User';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private permissionRepository: Repository<Permission>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Role)
    private roleRepository: Repository<Role>,
    @InjectRepository(TableAccess)
    private tableAccessRepository: Repository<TableAccess>,
    @InjectRepository(DatabaseAccess)
    private databaseAccessRepository: Repository<DatabaseAccess>,
    @InjectRepository(RolePermission)
    private rolePermissionRepository: Repository<RolePermission>,
  ) {}

  async getPermissions() {
    try {
      const permissions = await this.permissionRepository.find();
      return {
        code: 0,
        data: permissions,
        msg: '获取权限列表成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: [],
        msg: `获取权限列表失败: ${errMsg}`,
      };
    }
  }

  async getPermissionById(id: number) {
    try {
      const permission = await this.permissionRepository.findOne({
        where: { id },
      });
      if (!permission) {
        throw new NotFoundException(`ID为${id}的权限不存在`);
      }
      return {
        code: 0,
        data: permission,
        msg: '获取权限成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: errMsg,
      };
    }
  }

  async createPermission(permissionData: Partial<Permission>) {
    try {
      const newPermission = this.permissionRepository.create(permissionData);
      const savedPermission =
        await this.permissionRepository.save(newPermission);
      return {
        code: 0,
        data: savedPermission,
        msg: '创建权限成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `创建权限失败: ${errMsg}`,
      };
    }
  }

  async updatePermission(id: number, permissionData: Partial<Permission>) {
    try {
      const permission = await this.permissionRepository.findOne({
        where: { id },
      });
      if (!permission) {
        throw new NotFoundException(`ID为${id}的权限不存在`);
      }

      await this.permissionRepository.update(id, permissionData);
      const updatedPermission = await this.permissionRepository.findOne({
        where: { id },
      });

      return {
        code: 0,
        data: updatedPermission,
        msg: '更新权限成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `更新权限失败: ${errMsg}`,
      };
    }
  }

  async deletePermission(id: number) {
    try {
      const permission = await this.permissionRepository.findOne({
        where: { id },
      });
      if (!permission) {
        throw new NotFoundException(`ID为${id}的权限不存在`);
      }

      await this.permissionRepository.delete(id);
      return {
        code: 0,
        data: null,
        msg: '删除权限成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: null,
        msg: `删除权限失败: ${errMsg}`,
      };
    }
  }

  async getPermissionUsers(id: number) {
    try {
      const permission = await this.permissionRepository.findOne({
        where: { id },
      });
      if (!permission) {
        throw new NotFoundException(`ID为${id}的权限不存在`);
      }

      // 查找直接通过表级权限关联的用户
      const tableAccesses = await this.tableAccessRepository.find({
        where: { PermissionId: id },
        relations: ['user'],
      });

      // 查找直接通过数据库级权限关联的用户
      const databaseAccesses = await this.databaseAccessRepository.find({
        where: { PermissionId: id },
        relations: ['user'],
      });

      // 查找通过角色关联的用户
      const rolePermissions = await this.rolePermissionRepository.find({
        where: { PermissionId: id },
        relations: ['role'],
      });

      const roleIds = rolePermissions.map((rp) => rp.RoleId);

      // 获取拥有这些角色的用户
      const users = await this.userRepository
        .createQueryBuilder('user')
        .innerJoin('user.roles', 'role', 'role.id IN (:...roleIds)', {
          roleIds,
        })
        .getMany();

      // 合并所有用户并去重
      const tableAccessUsers = tableAccesses.map((ta) => ta.user);
      const databaseAccessUsers = databaseAccesses.map((da) => da.user);

      const allUsers = [...tableAccessUsers, ...databaseAccessUsers, ...users];

      // 去重
      const uniqueUsers = allUsers.filter(
        (user, index, self) =>
          index === self.findIndex((u) => u.id === user.id),
      );

      return {
        code: 0,
        data: uniqueUsers,
        msg: '获取拥有该权限的用户成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: [],
        msg: `获取拥有该权限的用户失败: ${errMsg}`,
      };
    }
  }

  async getPermissionRoles(id: number) {
    try {
      const permission = await this.permissionRepository.findOne({
        where: { id },
      });
      if (!permission) {
        throw new NotFoundException(`ID为${id}的权限不存在`);
      }

      // 查找拥有该权限的角色
      const rolePermissions = await this.rolePermissionRepository.find({
        where: { PermissionId: id },
        relations: ['role'],
      });

      const roles = rolePermissions.map((rp) => rp.role);

      return {
        code: 0,
        data: roles,
        msg: '获取拥有该权限的角色成功',
      };
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : '未知错误';
      return {
        code: 1,
        data: [],
        msg: `获取拥有该权限的角色失败: ${errMsg}`,
      };
    }
  }
}
